﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;

namespace Common.Security
{
    /// <summary>
    /// Extensions to interop between <see cref="SecureString"/> and byte[].
    /// </summary>
    public static class ByteArrayExtension
    {
        /// <summary>
        /// Decrypts an array of bytes and returns it as <see cref="SecureString"/>.
        /// </summary>
        /// <param name="array"></param>
        /// <returns>decrypted secure string</returns>
        public static SecureString AsDecryptedSecureString(this byte[] array)
        {
            Contract.Requires(array != null);

            var pwdGen = new Common.Security.MasterPasswordGenerator();
            var ch = new Common.Security.CryptoHelper();

            var pwdString = Encoding.Unicode.GetString(array);

            var decryptedSecureString = ch.DecryptToSecureString(pwdString, pwdGen.GetPassword());
            return decryptedSecureString;
        }

        /// <summary>
        /// Encrypts the passed <see cref="SecureString"/> and returns it as array of bytes.
        /// </summary>
        /// <param name="secString"></param>
        /// <returns>encrypted byte array</returns>
        public static byte[] AsEncryptedByteArray(this SecureString secString)
        {
            Contract.Requires(secString != null);

            var pwdGen = new Common.Security.MasterPasswordGenerator();
            var ch = new Common.Security.CryptoHelper();

            var encryptedString = ch.Encrypt(secString, pwdGen.GetPassword());
            return Encoding.Unicode.GetBytes(encryptedString);
        }
    }
}
